package com.whisperarts.financer.app.dialogs;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.TableWrapLayout;

import com.whisperarts.financer.app.utils.UIUtils;
import com.whisperarts.financer.dao.AccountsDAO;
import com.whisperarts.financer.model.transaction.Category;

/**
 * @author AD
 *
 */
public class AccountSelectionDialog extends Dialog implements SelectionListener {

	protected Text textName;
	
	private FormToolkit toolkit;

	private String shellTitle;	

	private final Shell parentShell;
	
	protected Combo comboCategories;

	private Category category;

	private String name;

	protected Button buttonIncome, buttonExpense;
	
	private boolean income = false;

	private int parentId;
	
	private int depth = 0;

	private final List<Category> categories = new ArrayList<Category>();

	private final List<String> items = new ArrayList<String>();

	public AccountSelectionDialog(Shell parentShell) {
		super(parentShell);
		this.parentShell = parentShell;
	}

	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		shellTitle = "Add new category";
		newShell.setText(shellTitle);
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		toolkit = new FormToolkit(parent.getDisplay());
		
		Form form = toolkit.createForm(parent);
		form.setText("New category");
		toolkit.decorateFormHeading(form);
		toolkit.paintBordersFor(form.getBody());

		TableWrapLayout layout = new TableWrapLayout();
		layout.numColumns = 1;
		form.getBody().setLayout(layout);

		Composite composite = toolkit.createComposite(form.getBody());

		toolkit.adapt(composite);

		GridLayout glayout = new GridLayout(2, false);
		composite.setLayout(glayout);

		toolkit.createLabel(composite, "&Name:");
		textName = new Text(composite, SWT.BORDER);
		textName.setLayoutData(new GridData(GridData.FILL, GridData.FILL,
				true, false));

		toolkit.createLabel(composite, "&Parent:");

		comboCategories = new Combo(composite, SWT.READ_ONLY);
		comboCategories.setItems(getItems());
		comboCategories.select(0);
		comboCategories.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (categories.get(comboCategories.getSelectionIndex()).isIncome()) {
					buttonIncome.setSelection(true);
					buttonExpense.setSelection(false);
					income = true;
				} else {
					buttonExpense.setSelection(true);
					buttonIncome.setSelection(false);
					income = false;
				}

			}
		});

		
		toolkit.createLabel(composite, "&Category type:");
		Composite radioComposite = toolkit.createComposite(composite, SWT.NONE);
		radioComposite.setLayout(new GridLayout(2, true));

		buttonExpense = toolkit.createButton(radioComposite, "Expense", SWT.RADIO);
		buttonExpense.setSelection(true);
		buttonExpense.addSelectionListener(this);
		buttonIncome = toolkit.createButton(radioComposite, "Income", SWT.RADIO);
		buttonIncome.addSelectionListener(this);
		
		fillData();
		
		composite.pack();
		
		return composite;
	}

	
	private String[] getItems() {
		categories.addAll(AccountsDAO.getCategories().values());
		formStructure(AccountsDAO.getCategories().get(0), getExludeCategory());
		
//		for (int i = 0; i < stringItems.length; i++) {
//			stringItems[i] = items.get(i);
//		}
		return items.toArray(new String[0]);
	}
	
	protected Category getExludeCategory() {
		return null;
	}

	/**
	 * Adds "-" to categories names according to their depth and puts them in correct order in items list
	 * @param rootCategory
	 */
	private void formStructure(Category rootCategory, Category excludeCategory) {
		int localDepth = depth++;
		for (Category category : rootCategory.getSub()) {	
			if (category.equals(excludeCategory))
				continue;
			name = category.getName(); 
			for (int i = 0; i < localDepth; i++) {
				name = "-" + name;
			}
			items.add(name);
			formStructure(category, excludeCategory);			
		}
		depth--;
	}

		
	protected void fillData() {
	}

	@Override
	protected void okPressed() {		
		name = textName.getText();
		
		if ("".equals(name.trim())) {
			MessageDialog.openError(getShell(), "Invalid Title",
			"Title field must not be blank.");
			return;
		}
		
		if (isNameExists(name)) {
			MessageDialog.openError(parentShell, "Error", "Category " + name + " already exist. Choose another name");
			return;
		}
	
		parentId = categories.get(comboCategories.getSelectionIndex()).getId();
		
		createCategory();
		super.okPressed();
	}

	protected boolean isNameExists(String name) {
		if (UIUtils.checkCategoryName(name)) {
			return true;
		}
		return false;
	}
	
	protected void createCategory() {
		category = getCategoryToCreate();
		category.setName(name);
		category.setIncome(income);
		category.setParentId(parentId);
		System.out.println();

	}

	protected Category getCategoryToCreate() {
		return new Category();
	}

	public Category getCategory() {		
		return category;
	}

	@Override
	public void widgetSelected(SelectionEvent e) {
		income = e.getSource().equals(buttonIncome);
		System.out.println(income);
	}

	@Override
	public void widgetDefaultSelected(SelectionEvent e) {
	}
}
